
layui.use(['form', 'layer', 'table', 'formSelects'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;
    var formSelects = layui.formSelects;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var detail_url = $('.detail_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var check_buy_product_url = $('.check_buy_product_url').val();

    var select_products_url = $('.select_products_url').val();


    if($('#memberlevelIds').length > 0){
        formSelects.render('memberlevelIds');
    }
    if($('#storeIds').length > 0){
        formSelects.render('storeIds');
    }

    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            {field: 'id', title: '序号', align:'center', minWidth:140},
            {field: 'buy_product_name', title: '购买商品', align:'center', minWidth:110},
            {field: 'gift_product_name', title: '赠送商品', align:'center', minWidth:110},
            {field: 'buy_num', title: '买赠数量', align:'center', templet:function(data){
                return '买' + data.buy_num + '赠' + data.gift_num;
            }},
            {field: 'to_users', title: '面向用户', align:'center', minWidth:240},
            {field: 'range', title: '适用范围', align:'center', minWidth:240},
            {field: 'create_date', title: '创建日期', align:'center',  sort: true},
            {title: '操作', fixed:"right", align:"center", minWidth:160, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        var name = $('.searchBox').find('input[name=name]').val();
        if(name != '' || act_status != '' || range_date != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: name,
                }
            });
        }else{
            layer.msg("请选择筛选条件");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("tableList", {
            where: {
                name: '',
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // 删除
    /*$('.del-btn').on('click', function(){
        layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });*/

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: 1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '650px'
            , top: 0
            , content: content
        });
    }

    // 面向用户
    if($('.to_user_type').attr('data-value')){
        initToUserType($('.to_user_type').attr('data-value'));
    }
    function initToUserType(value){
        if (value == 3) {
            $('.user_ids-div').css('display', 'block');
        } else {
            $('.user_ids-div').css('display', 'none');
        }
    }
    // 切换面向用户
    form.on('radio(to_user_type)', function (data) {
        var value = data.value;
        initToUserType(value);
    });

    // 适用范围
    if($('.range').attr('data-value')){
        initRange($('.range').attr('data-value'));
    }
    function initRange(value){
        if (value == 3) {
            $('.store_ids-div').css('display', 'block');
        } else {
            $('.store_ids-div').css('display', 'none');
        }
    }
    // 切换适用范围
    form.on('radio(range)', function (data) {
        var value = data.value;
        initRange(value);
    });

    // 自定义验证规则
    form.verify({
        buy_product_id: function(value){
            if (value == '') {
                return '请选择购买商品';
            }
        },
        gift_product_id: function(value){
            if (value == '') {
                return '请选择赠送商品';
            }
        },
        buy_num: function(value){
            if (value == '' || value == 0) {
                return '购买数量不能为空';
            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '购买数量格式不正确，应为大于0的正整数';
                }
            }
        },
        gift_num: function(value){
            if (value == '' || value == 0) {
                return '赠送数量不能为空';
            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '赠送数量格式不正确，应为大于0的正整数';
                }
            }
        },
        to_users: function(value){
            var to_user_type = $('input[name=to_user_type]:checked').val();
            if(to_user_type == 3){
                if (value == '') {
                    return '请选择会员';
                }
            }
        },
        store_ids: function(value){
            var range = $('input[name=range]:checked').val();
            if(range == 3){
                if (value == '') {
                    return '请选择门店';
                }
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        if(data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }
        // 面向用户
        if(data.field.to_user_type != 3) {
            data.field.to_users = '';
        }
        // 适用范围
        if(data.field.range != 3) {
            data.field.store_ids = '';
        }

        var buy_product_id = $('.buy_product_id').val();
        var ori_buy_product_id = $('.buy_product_id').attr('data-value');

        if(buy_product_id != ori_buy_product_id){
            var url = check_buy_product_url;
            $.ajax({
                url: url,
                type: 'POST',
                data: {'product_id': buy_product_id},
                dataType : 'json',
                success: function (res) {
                    if(res.status == 1){
                        layer.confirm('该购买商品已存在，是否要覆盖之前的数据？', {icon: 3, title: '提示信息'}, function (index) {
                            layer.close(index);
                            submitForm(data);
                        });
                    }else{
                        submitForm(data);
                    }
                }
            });
            return false;
        }

        submitForm(data);
    });

    // 表单提交
    function submitForm(data){
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    }

    // 选择 购买/赠送商品
    $('.select-products').on('click', function(){
        var content = select_products_url;
        content += '?type=' + $(this).attr('data-type');
        var index = layer.open({
            title : "选择商品",
            type : 2,
            area : ["800px", "600px"],
            content : content,
            success : function(layero, index){
                form.render();
            }
        });
    });
});